<template>
	<view>
		<view>
			<view class="num">
				{{list_index+1}}/{{list.length}}
			</view>
			<view class="box-sub" v-if="list.length > 0">
				<view class="img-box" v-if="list[list_index].img">
					<image @click="previewImage(list[list_index].img)" mode="aspectFit" :src="list[list_index].img"
						alt=""></image>
				</view>
				<view class="index-txt">
					<text>{{list[list_index].count}}</text>
					<text>第{{list_index+1}}组题目</text>
				</view>
				<view class="" style="padding-bottom: 200rpx;">
					<view class="content-box" v-for="(items, index) in data.questions">
						<view class="title">
							<view class="title-l0ine"></view>
							<text
								class="title-txt">{{index + 1  +'、'+items.title}}({{score}}分)({{data.tqType == 1 ? '单选':(data.tqType == 3 ? '判断' : '多选')}})</text>
						</view>
						<view class="uni-px-5 uni-pb-5">
							<kevy-radio :modeType="modeType" :tqType="data.tqType" v-if="items.options.length > 0"
								:items="items.options" :idx="data.questions[index].idx" :fontSize="28" color="#E23321"
								:iconSize="30" iconColor="#329cfe" @radioClick="myClick($event, index)"></kevy-radio>
						</view>
						<template v-if="model == null">
							<view class="prompt uni-px-5 uni-pb-5" v-if=" modeType == 4 ? false : true ">
								<view>正确答案：<text class="stroke"> {{items.answer}}</text></view>
								<view>
									解析：<text class="stroke">{{ items.analysis || '暂无' }}</text>
								</view>
							</view>
						</template>
						<template v-else>
							<view class="prompt uni-px-5 uni-pb-5">
								<view>你选择的答案
									{{ items.userAnswer ==  ''  ? '未做' : items.userAnswer }} | 正确答案：<text
										class="stroke"> {{items.answer}}</text>
								</view>
								<view>
									解析：<text class="stroke">{{ items.analysis || '暂无' }}</text>
								</view>
							</view>
						</template>
					</view>
				</view>
			</view>
			<view v-else>
				<q-previewImage :show="true" ref="previewImage" :urls="imgs"></q-previewImage>
			</view>
			<view class="btn-box" v-if="list.length != 1">
				<view class="btn-up btn" @click="up">
					{{list_index != 0 ? '上一组' : '没有了'}}
				</view>
				<view class="btn-down btn" @click="down">
					{{list_index+1 < list.length ? '下一组' : '没有了'}}
				</view>
			</view>
			<view class="btm-btn">
				<button class="btn" @click="submitPaper">交卷</button>
				<button class="btn" @click="AnswersListShow">答题卡</button>
			</view>
		</view>
		<uni-popup ref="paperPopup" type="bottom" @change="paperPopupChange">
			<view class="paper-box" v-if="params_data.list.length > 0">
				<view @click="closePaperClose" class="iconfont icon-cuowu closeIcon"></view>
				<view class="submitPopupTxt">
					<text class="popup-title" style="color: #f00;">{{answers_list==1 ? "答题卡" : "交卷提示"}}</text>
					<view class="popup-sub" v-if="answers_list==0">你还有<text
							style="color: #f00;">{{result_data.none_data.length}}</text>道题没做，<text>确定交卷吗？</text>
					</view>
					<view class="popup-sub" v-else>你还有<text
							style="color: #f00;">{{result_data.none_data.length}}</text>道题没做
					</view>
				</view>
				<view class="paper-list">
					<uni-row :gutter="5">
						<uni-col :span="4" class="subject-list" v-for="(item, index) in params_data.list">
							<view class="subject-box" @click="clickItem(item)">
								<text class="subject-title">图{{index+1}}</text>
								<view class="subject-num">
									<text :class="[
										'btnMin',  
										type == 1 ? 'right' : (i.userAnswer === i.answer ? 'right' : 'fault'), 
										!i.userAnswer ? 'none' : '' ]" v-for="(i, idx) in item.questions">{{idx+1}}
									</text>
								</view>
							</view>
						</uni-col>
					</uni-row>
				</view>
				<view class="submitPopupBtn" v-if="answers_list==0">
					<button class="close-btn" @click="closePaperClose" type="default">取消</button>
					<button class="submit-btn" @click="confirmPaper" type="primary">确定交卷</button>
				</view>
			</view>
		</uni-popup>

		<!-- 考试成绩 -->
		<uni-popup ref="submitPopup" :is-mask-click="false" type="center">
			<view class="submit-popup-box">
				<view class="submitPopupTxt">
					<text class="popup-title">考试成绩</text>
					<view class="popup-sub">
						<text class="submit-name">{{ user_info.nickname }}-{{ user_info.username }}</text>
						<text class="submit-type">{{ opc_name }}</text>
					</view>
					<view class="fraction" v-if="type != 0">
						<text :style="{'color': pass_num>result_data.total_score_right?'#f00':'#329cfe'}"
							class="fraction-num">{{ result_data.total_score_right }}</text>分
					</view>
					<!-- {{result_data.none_data}} -->
					<text class="timePaper">答题用时：{{ timeDifference(start_time, end_time) }}</text>
					<view class="prompt-box">
						<view style="background: #f00;color: #fff;" class="prompt-box-txt">
							<text>答错</text>
							<text>{{ result_data.fault_data.length }}</text>
						</view>
						<view style="background: #329cfe;color: #fff;" class="prompt-box-txt">
							<text>答对</text>
							<text>{{ result_data.right_data.length }}</text>
						</view>
						<view v-if="result_data.none_data.length > 0" style="background-color: #b1b1b1;color: #fff;"
							class="prompt-box-txt">
							<text>未答</text>
							<text>{{ result_data.none_data.length }}</text>
						</view>
					</view>
					<view class="submit-list">
						<button v-if="type == 1" size="mini" @click="practiceError" class="list-btn"
							type="warn">错题练习</button>
						<button v-if="type == 1" size="mini" @click="lockpaper" class="list-btn"
							type="primary">查看试卷</button>
						<button @click="closeBlack" size="mini" class="list-btn" type="default">关 闭</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getSubPaper,
		addSubPaper,
		getSubPaperDetail
	} from '@/api/index.js'
	import {
		timeDifference
	} from '@/utils/index'
	export default {
		data() {
			return {
				timeDifference,
				custom: 25,
				checkedIdx: '',
				modeType: 3,
				type: '', // 0练习模式 1 模拟考试
				list_index: 0,
				opc: '',
				opc_name: '',
				data: {},
				list: [],
				score: '',
				start_time: '',
				end_time: '',
				params_data: [],
				result_data: {},
				user_info: {},
				plan_name: '',
				pass_num: 80,
				sub_score: '10',
				answers_list: 0,
				paper_info: {},
				model: null, //1 错题练习 2 试卷查看
				id: null,
				imgs: [],
			}
		},

		created(val) {

		},
		onLoad(val) {
			// console.log(val);
			if (val.hasOwnProperty('id')) {
				this.id = val.id
				this.model = val.model
				uni.setNavigationBarTitle({
					title: val.model == 1 ? '错题练习' : '试卷查看'
				})
				this.type = 0
			} else {
				this.type = val.type // type 0 练习模式 1 模拟考试
			}
			//model 1 错题练习 2 试卷查看
			this.opc = uni.getStorageSync('opc')

			this.opc_name = uni.getStorageSync('opcName')
			this.modeType = val.type == 1 ? '4' : '3' //kevy-radio=> 4 模拟考试 3 练习模式
			this.start_time = new Date().getTime()
			this.score = 100 / this.custom / 2
			this.user_info = uni.getStorageSync('userinfo')
			// console.log(this.modeType);
			this.loadData()
			// this.$refs.paperPopup.open()
			// console.log(this.data);
		},
		methods: {
			previewImage(val) {
				uni.previewImage({
					urls: [val]
				})
			},
			loadData() {
				const params = {}
				if (this.id != null) {
					params.id = this.id
					getSubPaperDetail(params).then(res => {
						if (this.model == 2) {
							this.list = this.addBzAnswer(res.data.list)
						} else {
							// 错题回顾
							this.list = this.addBzAnswer(res.data.errList)
						}
						this.data = this.list[this.list_index]
					})
				} else {
					params.type = this.type
					params.opc = this.opc
					if (this.type == 1) {
						params.custom = this.custom
					}
					getSubPaper(params).then(res => {
						this.list = this.type == 1 ? this.addBzAnswer(res.data.list) : this.addBzAnswer(res.data
							.list).sort((a, b) => a.sort - b.sort)
						this.data = this.list[this.list_index]
						console.log(this.list);
					})
				}

			},
			addBzAnswer(data) {
				// 遍历每个项目  
				data.forEach(questionGroup => { // 遍历每个问题组（即每个子数组）  
					questionGroup.questions.forEach(question => { // 遍历每个问题  
						const answer = question.answer;
						question.options.forEach(option => { // 遍历每个问题的选项 
							option.bzAnswer = answer; // 为每个选项添加bzAnswer属性，并设置其值为问题的answer  
							option.userAnswer = "";
							option.texts = this.type == 1 ? option.text.replace(/<[^>]+>/g, '') :
								option.text
						});
					});
				});
				return data;
			},
			markToRed(val, mark, letter) {
				if (mark == null) {
					return val
				}

				let idex = mark // 转化成以下形式
				let starStr = '<span style="color:#f00;text-decoration:underline;font-weight:bold;">' // 开头添加的字符串
				let endStr = '</span>' //尾添加的字符串
				let string = val
				let idxs = idex.split('-')
				let obj = {}
				// 根据标识是否加粗文字
				if (idex != '') {
					let obj = {}
					for (let i = 0; i < idxs.length; i++) {
						obj[idxs[i]] = `${starStr}${idxs[i]}${endStr}`
					}
					for (let [key, value] of Object.entries(obj)) {
						string = string.replace(new RegExp(key, "g"), value);
					}
					return string
				} else {
					return string
				}
			},
			up() {
				if (this.list_index == 0) {
					return uni.showToast({
						title: "已经是第一题了",
						icon: "none"
					})
				}
				this.$nextTick(() => {
					this.list_index--
					this.data = this.list[this.list_index]
				})
			},
			down() {
				if (this.list_index + 1 >= this.list.length) {
					return uni.showToast({
						title: "已经最后一题了",
						icon: "none"
					})
				}
				this.$nextTick(() => {
					this.list_index++
					this.data = this.list[this.list_index]
				})
			},
			myClick(val, fidx) {
				this.checkedIdx = val.index
				this.list[this.list_index].questions[fidx].options[val.index].checked = !this.list[this.list_index]
					.questions[fidx].options[val.index].checked
				if (this.list[this.list_index].tqType == 2) {
					let item = val.item.map(e => {
						if (e.checked) {
							return e.value;
						}
					}).filter(value => value !== undefined);
					console.log(item);
					this.list[this.list_index].questions[fidx].userAnswer = item.join()
				} else {
					this.list[this.list_index].questions[fidx].userAnswer = val.answer
				}
				this.list[this.list_index].questions[fidx].options[val.index].userAnswer = val.answer
				this.list[this.list_index].questions[fidx].idx = val.index
			},
			// 交卷 有二次确认
			submitPaper() {
				this.params_data = this.transformData(this.list)
				this.result_data = this.answerData(this.params_data.list)
				// 判断题目做完没
				// console.log(this.result_data.none_data.length != 0, this.history_type == undefined);
				if (this.result_data.none_data.length != 0) {
					return this.$refs.paperPopup.open()
				}
				// type 1 模拟考试
				if (this.type == 1) {
					return this.submitSubPaper()
				}
				// type 0 练习模式
				if (this.type == 0) {
					this.end_time = new Date().getTime()
					// console.log(this.result_data);
					return this.$refs.submitPopup.open()
				}

			},
			submitSubPaper() {
				this.end_time = new Date().getTime()
				console.log(this.params_data);
				addSubPaper(this.params_data).then(res => {
					this.paper_info = res.data
					this.id = res.data.id
					this.$refs.paperPopup.close()
					this.$refs.submitPopup.open()

				})
			},
			closePaperClose() {
				this.$refs.paperPopup.close()
			},
			AnswersListShow() {
				this.answers_list = 1
				this.params_data = this.transformData(this.list)
				this.result_data = this.answerData(this.params_data.list)
				this.$refs.paperPopup.open()
			},
			clickItem(item) {
				this.list_index = item.index
				this.data = this.list[this.list_index]
				this.$nextTick()
				this.$refs.paperPopup.close()
			},
			// 确定交卷
			confirmPaper() {
				// 练习模式不走接口
				console.log(this.id);
				if (this.type == 0 || this.id != null) {
					this.end_time = new Date().getTime()
					this.$refs.paperPopup.close()
					this.$refs.submitPopup.open()
					return
				}

				this.submitSubPaper()
			},
			closeBlack() {
				this.$refs.submitPopup.close()
				uni.navigateBack()
			},
			// 错题练习
			practiceError() {
				uni.redirectTo({
					url: `/pages/operation/operation?id=${this.id}&type=0&model=1`
				});
			},
			// 查看试卷
			lockpaper() {
				uni.navigateTo({
					url: `/pages/operation/operation?id=${this.id}&type=0&model=2`
				})

			},
			paperPopupChange(e) {
				if (!e.show) {
					this.answers_list = 0
				}
			},
			answerData(data) {
				let total_score_right = 0; // 仅用于存储right_data中的题目总分  
				const none_data = [];
				const fault_data = [];
				const right_data = [];
				data.forEach(section => {
					section.questions.forEach(question => {

						if (question.userAnswer === undefined || question.userAnswer === '') {
							none_data.push({
								qid: question.qid,
								answer: question.answer,
								score: question.score
							});
						} else if (question.userAnswer !== question.answer) {
							fault_data.push({
								qid: question.qid,
								answer: question.answer,
								score: question.score,
								userAnswer: question.userAnswer
							});
						} else {
							right_data.push({
								qid: question.qid,
								answer: question.answer,
								score: question.score,
								userAnswer: question.userAnswer
							});
							total_score_right += question.score; // 仅对right_data中的题目累加分数  
						}
					});
				});

				// 如果你还需要所有题目的总分，可以额外计算或者保留之前的totalScore变量  
				let totalScoreAll = none_data.reduce((acc, item) => acc + item.score, 0) +
					fault_data.reduce((acc, item) => acc + item.score, 0) +
					right_data.reduce((acc, item) => acc + item.score, 0);

				return {
					total_score_right: total_score_right.toString(), // right_data中的题目总分  
					totalScoreAll: totalScoreAll.toString(), // 所有题目的总分（如果需要的话）  
					none_data: none_data,
					fault_data: fault_data,
					right_data: right_data
				};
			},
			transformData(rawData) {
				const transformedData = {
					list: [],
					opc: this.opc, // 假设所有组的 opc 都相同  
					startTime: this.start_time // 当前时间  
				};
				rawData.forEach((group, index) => {
					const newGroup = {
						id: group.id,
						index: index,
						questions: group.questions.map(question => ({
							qid: question.id,
							answer: question.answer,
							score: question.answer == question.userAnswer ? (group.questions
								.length == 1 ? this.score * 2 : this.score) :
							0, // 假设每个问题的分数都是 25  
							userAnswer: question.userAnswer
						}))
					};
					transformedData.list.push(newGroup);
				});
				return transformedData;
			}
		}
	}
</script>

<style lang="less" scoped>
	page {
		background-color: #fff;
		height: 100%;
	}

	.h_100 {
		height: 100%;

		.box-sub {
			height: 100%;
		}

		.img-box {
			height: 100%;
		}
	}

	.num {
		position: fixed;
		right: 5rpx;
	}

	.content-box {
		.title {
			display: flex;
			padding: 15rpx 30rpx;

			.title-line {
				background: #E23321;
				width: 8rpx;
				// height: 34rpx;
				border-radius: 20rpx;
				margin-right: 10rpx;
			}

			.title-txt {
				font-size: 28rpx;
				font-weight: 600;
			}
		}
	}

	.img-box {
		padding: 20rpx;
		border-radius: 20rpx;
		overflow: hidden;
		height: 500rpx;
		text-align: center;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.index-txt {
		font-size: 36rpx;
		text-align: center;
	}

	.btn-box {
		display: flex;
		justify-content: space-around;
		padding-bottom: 80rpx;
		position: fixed;
		bottom: 30rpx;
		width: 100%;

		.btn {
			width: 290rpx;
			height: 80rpx;
			text-align: center;
			border-radius: 10rpx;
			line-height: 80rpx;
			font-weight: 500;
			font-size: 32rpx;
		}

		.btn-up {
			color: #2386FF;
			background: #EDF5FF;
		}

		.btn-down {
			color: #fff;
			background: #2386FF;
		}
	}

	.btm-btn {
		position: fixed;
		bottom: 0rpx;
		z-index: 2;
		width: 100%;
		display: flex;
		background-color: #f0f0f0;

		.btn {
			flex: 1;
		}
	}

	.paper-box {
		background-color: #fff;
		border-radius: 20rpx;
		min-height: 900rpx;

		.paper-list {
			// margin: 0 10rpx;
			padding: 0 10rpx;
			margin-bottom: 30rpx;
		}

		.btnMin {
			width: 100%;
		}


		.submitPopupBtn {
			display: flex;
			position: fixed;
			width: 100%;
			bottom: 0;

			.close-btn {
				flex: 1;
			}

			.submit-btn {
				flex: 1;
			}
		}


	}

	.submitPopupTxt {
		text-align: center;
		padding-bottom: 20rpx;

		.popup-title {
			display: block;
			padding: 10rpx 0;
			font-size: 40rpx;
		}

		.popup-sub {
			display: block;
			padding: 0 20rpx;
			font-size: 35rpx;
		}
	}

	.subject-list {
		text-align: center;
		display: inline-block;
		font-size: 26rpx;
		color: #1E1E20;
		margin-bottom: 10rpx;

		.subject-box {
			border: 1rpx solid #998282;
			margin: 2rpx;
			overflow: hidden;
			border-radius: 6rpx;
			background: #F8F8F8;
		}

		.subject-title {
			display: block;
		}

		.subject-num {
			border-top: 1rpx solid #998282;
			height: 40rpx;
			line-height: 40rpx;
			display: flex;
			justify-content: space-around;
			position: relative;
			// .subject-line {

			// }
		}

		.btnMin:first-child {
			::after {
				content: "";
				height: 40rpx;
				width: 1rpx;
				background: #998282;
				position: absolute;
				top: 50%;
				/* 将元素的顶部移动到父元素的中心 */
				left: 50%;
				/* 将元素的左侧移动到父元素的中心 */
				transform: translate(-50%, -50%);
				/* 使用 transform 调整元素自身的位置，使其中心点与父元素的中心点对齐 */
			}
		}

	}

	.closeIcon {
		position: absolute;
		right: 36rpx;
		top: 6rpx;
		font-size: 38rpx;
		z-index: 9;
	}

	.right {
		background: #329cfe;
		color: #fff;
	}

	.fault {
		background: #f00;
		color: #fff;
	}

	.none {
		background: #F8F8F8;
		color: #1E1E20;
	}

	.submit-popup-box {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 20rpx;
		width: 600rpx;

		.submitPopupTxt {}

		.popup-sub {
			padding: 5px 15rpx;
			font-size: 13px;
			border-bottom: 1px dashed #333;
		}

		.submit-name {
			display: block;
		}

		.fraction {
			display: flex;
			justify-content: center;
			align-items: baseline;
			border-bottom: 1px solid #a29f9f;

			.fraction-num {
				font-weight: bold;
				font-size: 68rpx;
			}
		}

		.timePaper {
			display: block;
			font-size: 30rpx;
			padding: 10rpx 0;
			border-bottom: 1px solid #a29f9f;
		}

		.submit-list {
			display: flex;

			.list-btn {
				// flex: 1;
			}
		}

		.prompt-box {
			display: flex;
			justify-content: space-around;
			border-bottom: 1px solid #a29f9f;
			margin-bottom: 30rpx;

			.prompt-box-txt {
				padding: 10rpx 0;
				border-left: 1px solid #a29f9f;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				flex: 1;
			}
		}
	}

	.prompt {
		display: flex;
		flex-direction: column;
		background-color: #8b8d8f;
		color: #fff;
		padding: 10rpx 20rpx;
	}

	.stroke {
		color: rgb(255, 0, 0);
		-webkit-text-stroke: 1rpx white;
		font-weight: 700;
	}
</style>